class Solution(object):
    def countComponents(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: int
        """
        self.part = n
        DP = [i for i in range(n)]

        def find(x):
            if DP[x] == x:
                return x
            else:
                DP[x] = find(DP[x])
                return DP[x]

        def union(x, y):
            rootx = find(x)
            rooty = find(y)
            if rootx != rooty:
                self.part -= 1
                if rootx < rooty:
                    DP[rooty] = rootx
                else:
                    DP[rootx] = rooty

        for item in edges:
            union(item[0], item[1])

        return self.part


data = Solution()
n = 5
edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
print(data.countComponents(n, edges))
n = 5
edges = [[0, 1], [1, 2], [3, 4]]
print(data.countComponents(n, edges))
